//
//  ComposeViewController.m
//  随拍
//
//  Created by lanou3g on 16/1/18.
//  Copyright © 2016年 Ashoka. All rights reserved.
//

#import "ComposeViewController.h"
#import "SPTextView.h"
#import "ComposeToolbar.h"
#import "PhotoView.h"
#import "ComposeMovieViewController.h"
#import "MovieView.h"
#import "ComposeVideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreLocation/CoreLocation.h>

@interface ComposeViewController () <UITextViewDelegate, ComposeToolbarDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,ComposeMovieViewControllerDelegate,CLLocationManagerDelegate >
@property (nonatomic ,assign) NSInteger location;

@property (nonatomic ,strong) SPTextView *textView;

@property (nonatomic ,strong) ComposeToolbar *toolbar;

@property (nonatomic ,weak) PhotoView *photosView;

@property (nonatomic ,strong) MovieView *movieView;

@property (nonatomic ,strong) NSString *moviePath;

@property (nonatomic ,strong) UIButton *placeBtn;
@property (nonatomic ,strong) NSString *currentPlace;
@property (nonatomic ,strong) CLLocationManager *locationManager;

@end

@implementation ComposeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    [self setTextView];
    [self setupToolbar];
    [self setupPhotosView];
    [self setPlace];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self setupMovieView];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.textView becomeFirstResponder];
}

- (void)setupNav{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStyleDone target:self action:@selector(send)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    NSString *name = @"用户名";
    NSString *prefix = @"发随拍";
    if (name) {
        UILabel *titleView = [[UILabel alloc] init];
        titleView.width = 200;
        titleView.height = 100;
        titleView.textAlignment = NSTextAlignmentCenter;
        // 自动换行
        titleView.numberOfLines = 0;
        titleView.y = 50;
        
        NSString *str = [NSString stringWithFormat:@"%@\n%@", prefix, name];
        
        // 创建一个带有属性的字符串（比如颜色属性、字体属性等文字属性）
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
        // 添加属性
        [attrStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:[str rangeOfString:prefix]];
        [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:[str rangeOfString:name]];
        titleView.attributedText = attrStr;
        self.navigationItem.titleView = titleView;
    } else {
        self.title = prefix;
    }

    
    
}

/**
 UITextField:
 1.文字永远是一行，不能显示多行文字
 2.有placehoder属性设置占位文字
 3.继承自UIControl
 4.监听行为
 1> 设置代理
 2> addTarget:action:forControlEvents:
 3> 通知:UITextFieldTextDidChangeNotification
 
 UITextView:
 1.能显示任意行文字
 2.不能设置占位文字
 3.继承自UIScollView
 4.监听行为
 1> 设置代理
 2> 通知:UITextViewTextDidChangeNotification
 */

- (void)setTextView{
    
    // 在这个控制器中，textView的contentInset.top默认会等于64
    SPTextView *textView = [[SPTextView alloc] init];
    // 弹簧效果
    textView.alwaysBounceVertical = YES;
    textView.frame = self.view.bounds;
    textView.delegate = self;
    textView.font = [UIFont systemFontOfSize:15];
    textView.placeholder = @"分享新鲜事...";
    [self.view addSubview:textView];
    self.textView = textView;

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:textView];
    
    // 键盘通知
    // 键盘的frame发生改变时发出的通知（位置和尺寸）
    //    UIKeyboardWillChangeFrameNotification
    //    UIKeyboardDidChangeFrameNotification
    // 键盘显示时发出的通知
    //    UIKeyboardWillShowNotification
    //    UIKeyboardDidShowNotification
    // 键盘隐藏时发出的通知
    //    UIKeyboardWillHideNotification
    //    UIKeyboardDidHideNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}

/**
 * 添加相册
 */
- (void)setupPhotosView
{
    PhotoView *photosView = [[PhotoView alloc] init];
    photosView.y = 100;
    photosView.width = self.view.width;
    // 随便写的
    photosView.height = self.view.height;
    [self.textView addSubview:photosView];
    self.photosView = photosView;
}
/*
- (void)setupMovieView{
    MovieView *movieView = [[MovieView alloc] init];
    movieView.y = 100;
    movieView.width = self.view.width;
    movieView.height = 300;
    
    NSURL *url = [NSURL URLWithString:self.moviePath];
    NSLog(@"0000000000000%@",self.moviePath);
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame = movieView.frame;
    [movieView.layer addSublayer:playerLayer];
    
    [self.textView addSubview:movieView];
//    self.movieView = movieView;
}
*/

/**
 * 添加工具条
 */
- (void)setupToolbar
{
    ComposeToolbar *toolbar = [[ComposeToolbar alloc] init];
    toolbar.width = self.view.width;
    toolbar.height = 44;
    toolbar.y = self.view.height - toolbar.height;
    toolbar.delegate = self;
    [self.view addSubview:toolbar];
    self.toolbar = toolbar;
    // inputAccessoryView设置显示在键盘顶部的内容
    //    self.textView.inputAccessoryView = toolbar;
    // inputView设置键盘
    //    self.textView.inputView = [UIButton buttonWithType:UIButtonTypeContactAdd];
}

#pragma mark - 监听方法
/**
 * 键盘的frame发生改变时调用（显示、隐藏等）
 */
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    //    if (self.picking) return;
    /**
     notification.userInfo = @{
     // 键盘弹出\隐藏后的frame
     UIKeyboardFrameEndUserInfoKey = NSRect: {{0, 352}, {320, 216}},
     // 键盘弹出\隐藏所耗费的时间
     UIKeyboardAnimationDurationUserInfoKey = 0.25,
     // 键盘弹出\隐藏动画的执行节奏（先快后慢，匀速）
     UIKeyboardAnimationCurveUserInfoKey = 7
     }
     */
    
    NSDictionary *userInfo = notification.userInfo;
    // 动画的持续时间
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 执行动画
    [UIView animateWithDuration:duration animations:^{
        // 工具条的Y值 == 键盘的Y值 - 工具条的高度
        if (keyboardF.origin.y > self.view.height) { // 键盘的Y值已经远远超过了控制器view的高度
            self.toolbar.y = self.view.height - self.toolbar.height;
        } else {
            self.toolbar.y = keyboardF.origin.y - self.toolbar.height;
        }
        
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)textDidChange{
   self.navigationItem.rightBarButtonItem.enabled = self.textView.hasText; 
}

- (void)cancel {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)send{
    NSLog(@"发送");
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)composeToolbar:(ComposeToolbar *)toolbar didClickButton:(ComposeToolbarButtonType)buttonType{
    
    switch (buttonType) {
        case ComposeToolbarButtonTypeCamera:
            [self openCamera];
            break;
            
        case ComposeToolbarButtonTypePicture:
            [self openAlbum];
            break;
            
        case ComposeToolbarButtonTypeMention:
            [self openMovie];
            
            break;
            
        case ComposeToolbarButtonTypeEmotion:
            [self openVideo];
            break;
            
        case ComposeToolbarButtonTypeTrend:
            
            break;
            
        default:
            break;
    }
}

#pragma mark  相机
- (void)openCamera{
    [self openImagePickerController:UIImagePickerControllerSourceTypeCamera];
}

- (void)openAlbum{
    [self openImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (void)openImagePickerController:(UIImagePickerControllerSourceType)type
{
    if (![UIImagePickerController isSourceTypeAvailable:type]) return;
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = type;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
/**
 * 从UIImagePickerController选择完图片后就调用（拍照完毕或者选择相册图片完毕）
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    // info中就包含了选择的图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    // 添加图片到photosView中
    [self.photosView addPhoto:image];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
}

#pragma mark  视频

- (void)openMovie{
    ComposeMovieViewController *movieVC = [ComposeMovieViewController new];
    [self.navigationController presentViewController:movieVC animated:YES completion:nil];
}

- (void)composeMovieViewSetMoviePath:(NSString *)moviePath{
    self.moviePath = moviePath;
}

- (NSString *)moviePath{
    if (!_moviePath) {
        _moviePath = [[NSString alloc] init];
    }
    return _moviePath;
}


#pragma mark 语音
- (void)openVideo{
    ComposeVideoViewController *videoVC = [ComposeVideoViewController new];
    [self.navigationController presentViewController:videoVC animated:YES completion:nil];
}

#pragma mark 显示所在位置

- (void)setPlace{
    self.placeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _placeBtn.frame = CGRectMake(0, 200, self.view.frame.size.width, 20);
    _placeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_placeBtn setTitle:@"显示位置" forState:UIControlStateNormal];
    [_placeBtn addTarget:self action:@selector(placeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _placeBtn.backgroundColor = [UIColor redColor];
    [self.view addSubview:_placeBtn];
}

- (void)placeButtonAction:(UIButton *)sender{
    if (_location == 0) {
        [self initializeLocationService];
        _location++;
    }else{
        [_placeBtn setTitle:@"显示位置" forState:UIControlStateNormal];
        _location = 0;
    }
}

- (void)initializeLocationService{
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    // 取得定位权限，有两个方法，取决于你的定位使用情况
    
    // 一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
    
    [_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
    
    [_locationManager startUpdatingLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    
    NSString *dd = [NSString stringWithFormat:@"%lf",newLocation.coordinate.longitude];
    
    NSLog(@"dd = %@",dd);
    
    NSString * cc = [NSString stringWithFormat:@"%lf",newLocation.coordinate.latitude];
    
    NSLog(@"cc = %@",cc);
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count > 0) {
            
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            
            self.currentPlace = placemark.name;
            
            NSLog(@"didian == %@",_currentPlace);
            
            [_placeBtn setTitle:_currentPlace forState:UIControlStateNormal];
            
            NSString *city = placemark.locality;
            
            if (!city) {
                
                city = placemark.administrativeArea;
                
            }
            
            NSLog(@"city = %@",city);
            
            NSString *city4 = city;
            
            NSLog(@"city4 == %@",city4);
            
            
        }else if (error == nil && [placemarks count] == 0){
            
            NSLog(@"00000");
            
            
        }else if (error != nil){
            
            NSLog(@"11111");
            
        }
    }];
    
    [manager stopUpdatingLocation];

    
    
}

@end
